package com.ilvyou.api.controller.common;

import com.ilvyou.api.common.Cache;
import com.ilvyou.api.common.Constant;
import com.ilvyou.api.bean.result.LoginResult;
import com.ilvyou.api.bean.result.Result;
import com.ilvyou.api.controller.BaseController;
import com.ilvyou.api.service.UserService;
import com.ilvyou.core.util.StringUtil;
import com.ilvyou.data.lhf.ScrAlipayEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by GuanYuCai on 2016/9/5 0005.
 */
@Controller
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/user/login", method = RequestMethod.POST)
    @ResponseBody
    public Result<LoginResult> login(@RequestParam String account, @RequestParam String password,
                                     @RequestParam String source) throws Exception {
        if (!verifySource(source)){
            return fail("登录设备不正确");
        }

        ScrAlipayEntity scrAlipay = userService.getScrAlipayEntityByAccount(account);

        if (scrAlipay == null || scrAlipay.getEnableflag() == 0){
            return fail("账户名不存在，请重新输入或注册新账号");
        }else if (scrAlipay.getLockflag() != 0){
            return fail("账户已被锁定");
        }else if (userService.checkPassword(scrAlipay, password)){
            return success(getResult(scrAlipay, source, ""));
        }else{
            return fail("密码错误，请重新输入或找回密码");
        }
    }

    @RequestMapping(value = "/user/register", method = RequestMethod.POST)
    @ResponseBody
    public Result register(@RequestParam String mobile, @RequestParam String password, @RequestParam String source,
                           @RequestParam String code, @RequestParam long sendid) throws Exception{
        if (!verifySource(source)){
            return fail("登录设备不正确");
        }

        if(!StringUtil.isMobile(mobile)){ //判断手机号是否为空
            return fail("手机号码格式不正确");
        }

        long time = userService.getSmsDeadline(sendid, code, mobile, Constant.SMSType.REGISTER);
        if(time < System.currentTimeMillis()){
            return fail("验证码不正确");
        }

        //Base64解密 密码字符串
        password = StringUtil.base64Decode(password);
        if (password.length() < 6 || password.length() > 20){
            return fail("密码必须是6到20位");
        }

        ScrAlipayEntity alipay = userService.addUser(mobile, password);
        if (alipay == null){
            return fail("该手机号已绑定乐汇付，请更换");
        }else{
            String uuid = StringUtil.UUID();
            Cache.Validation v = new Cache.Validation(mobile, time, Constant.SMSType.REGISTER);
            Cache.putValidation(uuid, v);
            return success(getResult(alipay, source, uuid));
        }
    }

    @RequestMapping(value = "/user/resetPassword", method = RequestMethod.POST)
    @ResponseBody
    public Result<String> resetPassword(@RequestParam String uuid, @RequestParam String password) throws Exception{
        Cache.Validation v = Cache.getValidation(uuid);
        if(v == null || (v.type != Constant.SMSType.RETRIEVE
                && v.type != Constant.SMSType.RESET_LOGIN)){
            return fail("验证码不正确");
        }

        userService.updatePassword(v.mobile, password);

        // 删除验证缓存
        Cache.removeValidation(uuid);
        return success("");
    }

    private LoginResult getResult(ScrAlipayEntity scrAlipay, String source, String uuid) throws Exception {
        long actId = scrAlipay.getActid();
        String token = "";
        LoginResult rs = new LoginResult();

        rs.setIfcomplete(userService.isCompleteInfo(actId) ? 0 : 1);

        token = StringUtil.UUID();
        rs.setToken(token);
        Cache.User user = new Cache.User();
        user.actId = actId;
        user.source = source;
        user.isComplete = rs.getIfcomplete() == 0;
        Cache.put(token, user);

        rs.setActid(actId + "");
        rs.setRealname(scrAlipay.getRealname());
        rs.setActname(scrAlipay.getActname());
        rs.setMobile(scrAlipay.getMobile());
        rs.setFaceurl(scrAlipay.getFaceurl());
        rs.setEmail(scrAlipay.getEmail());
        rs.setIdentity(scrAlipay.getBppagentcategory());
        rs.setUuid(uuid);

        //判断是否绑定旅赞
        rs.setBpploginname(StringUtil.isEmpty(scrAlipay.getBpploginname()) ? null : scrAlipay.getBpploginname());
        return rs;
    }

    private boolean verifySource(String source){
        return "Android".equals(source) || "IOS".equals(source);
    }
}
